$(function () {
  init()

  let countdown = 60

  // 获取验证码
  $('#getCode').off('click').on('click', function () {
    if ($('#mobile').val().length !== 11 ||
      !/^[0-9]*$/.test($('#mobile').val())) {
      utils.toast('手机号码格式错误')
      return
    }

    if (!$('#getCode').attr('class')) sendCode($('#mobile').val())
  })

  // 确认支付
  $('#buy').off('click').on('click', function () {
    if ($('.login').css('display') === 'block') {
      const mobile = $('#mobile').val()
      const code = $('#code').val()
      if (mobile.length !== 11 ||
        !/^[0-9]*$/.test(mobile)) {
        utils.toast('手机号码格式错误')
        return
      }
      if (code.length !== 4 ||
        !/^[0-9]*$/.test(code)) {
        utils.toast('验证码格式错误')
        return
      }

      login(mobile, code, submitOrder)
    } else {
      submitOrder()
    }
  })

  // 设置密码表单校验
  $('#password').off('input').on('input', function () {
    if ($('#password').val().length >= 6 &&
      $('#password').val().length <= 12 &&
      /^[0-9a-zA-Z]*$/.test($('#password').val())) {
      $('#passwordBtn').addClass('active')
    } else {
      $('#passwordBtn').removeClass('active')
    }
  })

  // 显示隐藏密码
  $('#showHidePassword').off('click').on('click', function () {
    if ($('#showHidePassword').attr('class') === 'hide') {
      $('#password').attr('type', 'text')
      $('#showHidePassword').attr('class', 'show')
    } else {
      $('#password').attr('type', 'password')
      $('#showHidePassword').attr('class', 'hide')
    }
  })

  // 设置密码
  $('#passwordBtn').off('click').on('click', function () {
    if ($('#password').val().length >= 6 &&
      $('#password').val().length <= 12 &&
      /^[0-9a-zA-Z]*$/.test($('#password').val())) {
      setPassword($('#password').val())
    } else {
      utils.toast('密码不符合要求')
    }
  })

  // 切换账号
  $('.switch-account').off('click').on('click', e => {
    account.ajax({
      type: 'DELETE',
      path: '/s/user/social/wx-jqfx',
      async: false
    })
    $('.user-info').hide()
    $('.login').show()
  })

  //启动计时器
  function setTime () {
    if (countdown > 0) {
      $('#getCode').attr('disabled', false)
      $('#getCode').text('重新发送(' + countdown + 's)')
      $('#getCode').addClass('disabled')
    } else {
      $('#getCode').attr('disabled', false)
      $('#getCode').text('发送验证码')
      $('#getCode').removeClass('disabled')
      countdown = 60
      return
    }
    countdown--

    setTimeout(arguments.callee, 1000)
  }

  // 发送验证码
  function sendCode (mobile) {
    $.ajax({
      type: 'POST',
      url: `${apiUrl}/s/user/sms/login`,
      data: JSON.stringify({mobile}),
      contentType: 'application/json',
      success: () => {
        setTime()
        utils.toast('验证码已经发送')
      },
      error: err => {
        const error = JSON.parse(err.response)
        console.error(error.message)
      }
    })
  }

  // 手机号登录
  function login (mobile, smsCode, callback) {
    $.ajax({
      type: 'POST',
      url: `${apiUrl}/s/user/login/sms`,
      data: JSON.stringify({
        mobile,
        smsCode,
        channel: utils.getQueryString('state') ? (utils.getQueryString('state').split('+++').length > 1 ? utils.getQueryString('state').split('+++')[1] : `${campaign}_share`) : `${campaign}_share`
      }),
      contentType: 'application/json',
      success: data => {
        countdown = 0
        window.userInfo = data
        window.access_token = data.access_token
        account._saveToken(data)
        if (utils.isWeChat()) {
          $.ajax({
            type: 'POST',
            url: `${apiUrl}/s/user/social`,
            headers: {'Authorization': `Bearer ${data.access_token}`},
            data: JSON.stringify({
              socialType: 'wx-jqfx',
              socialCode: utils.getQueryString('code')
            }),
            contentType: 'application/json',
            success: result => {
              account.socialBinded = true
              account._saveOpenId(result.socialId)
              window.openId = result.socialId
              callback()
            },
            error: err => {
              const error = JSON.parse(err.response)
              utils.toast(error.message)
              console.error(error.message)
            }
          })
        } else {
          callback()
        }
      },
      error: err => {
        const error = JSON.parse(err.response)
        console.error(error.message)
      }
    })
  }

  // 购买下单
  function submitOrder () {
    const accessString = window.localStorage.getItem('QKidsAccess')
    const access = JSON.parse(accessString)
    window.access_token = access.access_token
    const openId = window.localStorage.getItem('QKidsOpenId')
    window.openId = openId
    $.ajax({
      type: 'POST',
      url: `${apiUrl}/s/bills`,
      headers: {'Authorization': `Bearer ${access_token}`},
      data: JSON.stringify({
        openId,
        productId,
        payChannel: utils.isWeChat() ? 'weixin' : 'alipay',
        returnUrl: window.verifyUrl,
        tradeType: 'JSAPI'
      }),
      contentType: 'application/json',
      success: data => {
        //唤起微信支付
        if (data.status !== 'error') {
          if (utils.isWeChat()) {
            let jsApiParameters = JSON.parse(data.jsApiParameters)
            jsApiParameters.success = () => {
              analytics.send({
                event: avPrefix + '_pay_success',
                attr: {
                  _c: utils.getQueryString('state') ? (utils.getQueryString('state').split('+++').length > 1 ? utils.getQueryString('state').split('+++')[1] : `${campaign}_share`) : `${campaign}_share`
                }
              })
              addMarketingAction()
              if (!window.userInfo.isPasswordSet) $('.password-mask').css('display', 'block')
              else {
                $('.container').css('display', 'none')
                $('.verify-payment').css('display', 'block')
              }
              return true
            }
            wxconfig.pay(data.bill_id, productId, jsApiParameters)
          } else {
            window.location.href = data.url
          }
        } else {
          utils.toast('下单失败，请重试')
        }
      },
      error: err => {
        const error = JSON.parse(err.response)
        if (error.code === 'product.rejected.by.bought.products') utils.toast('您已经购买过100/4课时了')
        else console.error(error.message)
      }
    })
  }

  // 设置密码
  function setPassword (password) {
    $.ajax({
      type: 'POST',
      url: `${apiUrl}/s/user/password`,
      data: JSON.stringify({password}),
      headers: {'Authorization': `Bearer ${window.userInfo.access_token}`},
      contentType: 'application/json',
      success: () => {
        $('.password-mask').css('display', 'none')
        $('.container').css('display', 'none')
        $('.verify-payment').css('display', 'block')
      },
      error: err => {
        const error = JSON.parse(err.response)
        console.error(error.message)
      }
    })
  }

  // 用户转化成功统计
  function addMarketingAction () {
    if (window.clickId) {
      $.ajax({
        type: 'POST',
        url: `${apiUrl}/s/events/actions`,
        headers: {'Authorization': `Bearer ${window.userInfo.access_token}`},
        data: JSON.stringify({
          socialType: 'wx-jqfx',
          setId: 1106863299,
          url: window.location.href,
          clickId: window.clickId,
          actionParam: { value: 100 * 100 }
        }),
        contentType: 'application/json'
      })
    }
  }
})

function init () {
  window.avPrefix = 'p010'
  window.analytics = AV.analytics({
    appId: 'antYy9lOFi5mkU9QKjtYmRLM-gzGzoHsz',
    appKey: 'jqyWxLyobpsmdwsJddJlDheb',
    channel: utils.isWeChat() ? 'weixin' : ''
  })
  analytics.send({
    event: `${avPrefix}_open`,
    attr: {
      _c: utils.getQueryString('state') ? (utils.getQueryString('state').split('+++').length > 1 ? utils.getQueryString('state').split('+++')[1] : `${campaign}_share`) : `${campaign}_share`
    }
  })

  window.campaign = 'friend'
  window.campUrl = `${window.location.protocol}//${window.location.host}/wx/${campaign}`
  window.verifyUrl = `${window.location.protocol}//${window.location.host}/wx/verifypayment1/${productId}`
  window.apiUrl = 'https://gate.97kid.com'
  window.clickId = utils.getQueryString('state') ? utils.getQueryString('state').split('+++')[0] : ''

  window.account = new Account()
  account.forceLogin = false
  window.account = new Account()
  account.forceLogin = false
  account.getUserInfo((err, userInfo) => {
    if (!err) {
      console.log('已经登录')
      console.log(userInfo)
      if (userInfo.headerSmall) $('.user-info .avatar').attr('src', userInfo.headerSmall)
      $('.user-info .nickname').text(userInfo.nickname)
      $('.login').hide()
      $('.user-info').show()
    } else {
      console.log('没有登录')
      $('.login').show()
      $('.user-info').hide()
    }
  })

  setShare()
}

function setShare () {
  if (utils.isWeChat()) {
    window.wxconfig = new WxConfig(wechatConfig, 'friend')
    window.shareFlag = ''
    window.shareMsg = shareFlag => {
      return {
        title: '【Qkids久趣】4-12岁，在家跟北美外教学英语，新用户100元体验！',
        desc: '严选北美外教在线授课，创造趣味十足的课堂体验，让孩子爱学更有效。',
        link: `${window.location.protocol}//${window.location.host}/wx`,
        imgUrl: 'https://static-app.97kid.com/site-student/public/img/share.png',
        success: target => {
          analytics.send({
            event: `${avPrefix}_share_success`,
            attr: {
              target,
              _c: utils.getQueryString('state') ? (utils.getQueryString('state').split('+++').length > 1 ? utils.getQueryString('state').split('+++')[1] : `${campaign}_share`) : `${campaign}_share`
            }
          })
        }
      }
    }
    window.activeShare = shareFlag => {
      window.shareFlag = shareFlag || ''
      wxconfig.activeShare(shareFlag, '', shareMsg(shareFlag))
    }
  }
}
